package com.coolweather.zhoumo2;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;

import com.coolweather.zhoumo2.gson.Forecast;
import com.coolweather.zhoumo2.gson.Weather;
import com.coolweather.zhoumo2.service.AutoUpdateService;
import com.coolweather.zhoumo2.util.HttpUtil;
import com.coolweather.zhoumo2.util.Utility;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;
    private Button navButton;
    private String mWeatherId;
    private Weather weatherObi;
    private ImageView bingPicImg;
    private ScrollView weatherLayout;//1
    private TextView titleCity;//2
    private TextView titleUpdateTime;//3
    private TextView degreeText;//4
    private TextView weatherInfoText;//5
    private LinearLayout forecastLayout;//6
    private TextView aqiText;//7
    private TextView pm25Text;//8
    private TextView comfortText;//9
    private TextView carWashText;//10
    private TextView sportText;//11
    public SwipeRefreshLayout swipeRefresh;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //实现背景图与状态栏融合
        if (Build.VERSION.SDK_INT >=21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_weather);

        //String weatherString = "";

        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        titleCity =(TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
        degreeText =(TextView) findViewById(R.id.degree_text);
        weatherInfoText =(TextView) findViewById(R.id.weather_info_text);
        forecastLayout =(LinearLayout)findViewById(R.id.forest_layout);
        aqiText =(TextView)findViewById(R.id.aqi_text);
        pm25Text =(TextView)findViewById(R.id.pm25_text);
        comfortText =(TextView)findViewById(R.id.comfort_text);
        carWashText =(TextView)findViewById(R.id.car_wash_text);
        sportText = (TextView)findViewById(R.id.sport_text);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button)findViewById(R.id.nav_button);

        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);

        mWeatherId = getIntent().getStringExtra("weather_id");

        swipeRefresh =(SwipeRefreshLayout)findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.design_default_color_primary);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this);
        String weatherString = prefs.getString("weather",null);
        final String weatherId;

        Log.d("aa",mWeatherId);
        String address = "http://guolin.tech/api/weather?cityid="+ mWeatherId +"&key=bc0418b57b2d4918819d3974ac1285d9";
        //取出

        String bingPic = prefs.getString("bing_pic",null);
        if (bingPic != null){
            Glide.with(this).load(bingPic).into(bingPicImg);
        }else{
            loadBingPic();
        }
        //Log.d("aa2",weatherString);
        if (weatherString != null) {
            Weather weather =Utility.handleWeatherResponse(weatherString);
            weatherId = weather.basic.weatherId;
            showWeatherInfo(weather);
            Log.d("aa3","vsdmk");
        }else{
            weatherId = getIntent().getStringExtra("weather_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(weatherId);
            Log.d("aa4","vsdmk");
        }
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("aa3",weatherId);
                requestWeather(weatherId);
                //swipeRefresh.setRefreshing(false);
            }
        });

        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

    }

    public void requestWeather(final String mWeatherId){
        String weatherUrl = "http://guolin.tech/api/weather?cityid="+
                mWeatherId +"&key=bc0418b57b2d4918819d3974ac1285d9";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(WeatherActivity.this,"获取天气失败",Toast.LENGTH_SHORT).show();
                swipeRefresh.setRefreshing(false);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText =response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);
                //Weather weather = null;
                /*try {
                    weather = parseWeatherData(responseText);
                }catch (JSONException e){
                    e.printStackTrace();
                }
                final Weather finalWeather = weather;*/
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather != null && "ok".equals(weather.status)){
                            SharedPreferences.Editor editor = PreferenceManager.
                                    getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather",responseText);
                            editor.apply();
                            //showWeatherInfo(weather);
                        }else {
                            Toast.makeText(WeatherActivity.this,"获取天气失败",Toast.LENGTH_SHORT).show();
                        }
                        swipeRefresh.setRefreshing(false);
                        /*SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                        editor.putString("weather",responseText);
                        editor.apply();
                        dispWeather(finalWeather);*/
                    }
                });
            }
        });
        loadBingPic();
    }
    //处理并展示Weather实体1类中的数据
    private void showWeatherInfo(Weather weather){
        if (weather != null && "ok".equals(weather.status)) {
            String cityName = weather.basic.cityName;
            String updateTime = weather.basic.update.updateTime.split(" ")[1];
            String degree = weather.now.temperature + "℃";
            String weatherInfo = weather.now.more.info;
            titleCity.setText(cityName);
            titleUpdateTime.setText(updateTime);
            degreeText.setText(degree);
            weatherInfoText.setText(weatherInfo);
            forecastLayout.removeAllViews();
            for (Forecast forecast : weather.forecastList) {
                View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false);
                TextView dateText = (TextView) view.findViewById(R.id.date_text);
                TextView infoText = (TextView) view.findViewById(R.id.info_text);
                TextView maxText = (TextView) view.findViewById(R.id.max_text);
                TextView minText = (TextView) view.findViewById(R.id.min_text);
                dateText.setText(forecast.date);
                Log.d("aaaa9", "ancoad");
                infoText.setText(forecast.more.info);
                Log.d("aaaa1000", "ancoad");
                maxText.setText(forecast.temperature.max);
                Log.d("aaaa2000", "ancoad");
                minText.setText(forecast.temperature.min);
                Log.d("aaaa3000", "ancoad");
                forecastLayout.addView(view);
                Log.d("aaaa4000", "ancoad");
            }
            if (weather.aqi != null) {
                aqiText.setText(weather.aqi.city.aqi);
                pm25Text.setText(weather.aqi.city.pm25);
            }
            String comfort = "舒适度" + weather.suggestion.comfort.info;
            String carWash = "洗车指数" + weather.suggestion.carWash.info;
            String sport = "运动建议" + weather.suggestion.sport.info;
            comfortText.setText(comfort);
            carWashText.setText(carWash);
            sportText.setText(sport);
            weatherLayout.setVisibility(View.VISIBLE);
            Intent intent = new Intent(this, AutoUpdateService.class);
            startService(intent);
        }else{
            Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
        }
    }

    //加载背景图片
    private void loadBingPic(){
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
                    }
                });
            }
            /*@Override
            public void onFailure(Call call, IOException e){
                e.printStackTrace();
            }*/
        });
    }

    private void dispWeather2(String weatherString) throws JSONException {
        parseWeatherData(weatherString);
    }
    private void dispWeather(Weather weather){
        titleCity.setText(weather.basic.cityName);
    }


    private Weather parseWeatherData(String responseData) throws JSONException {
        JSONObject firstLevel = new JSONObject(responseData);
        JSONArray jsonArray = firstLevel.getJSONArray("HeWeather");
        String weatherContent = jsonArray.getJSONObject(0).toString();
        Log.d("aa",weatherContent);
        //weatherObi = new Gson().fromJson(weatherContent,Weather.class);
        Log.d("aa",weatherObi.basic.cityName);
        return new Gson().fromJson(weatherContent,Weather.class);
    }
}